#!/bin/env python3
#coding=utf-8
import hashlib
import time
import re
from lib.bottle import response, request
from lib.database.read import readMode
from lib.database.dbcenter import dbcenter
from random import randint

class Tools:
    
    covertime = 180
    
    @staticmethod
    def checkWords(st, reg):
        if re.match(reg, st) == None or st == None:
            return False
        return True
    
    @staticmethod
    def str2md5(st):
        hashobj = hashlib.md5()
        hashobj.update(st.encode('utf8'))
        return hashobj.hexdigest()

    @staticmethod
    def get_coverid():
        return str(randint(100000, 999999))

    @staticmethod
    def htmlfilter(st):
        return st.replace('&', '&amp;').replace("<", "&lt;").replace(">", "&gt;").replace(" ", "&nbsp;")

    @staticmethod
    def setcookie(key, val, max_age=10):
        response.set_cookie(
            key,
            val,
            max_age = max_age,
            httponly = False,
            path="/",
        )

    @staticmethod
    def getcookie(key):
        return request.get_cookie(key)

    @staticmethod
    def ipfilter(ip):
        return True


class User:

    def __init__(self, nick):
        self.nickname = nick
        self.mode = readMode()

    def repeat(self):

        data = self.mode.select(
            ["COUNT(1)"],
            {
                "text" : "nickname = %s;",
                "format": [self.nickname]
            },
            "users",
            True
        )
        num = data[0]
        if num == 0:
            return False
        return True

    def register(self, pwd):
        tools = Tools()
        password = tools.str2md5(pwd)
        unitid = tools.str2md5(self.nickname + str(time.time()))
        return self.mode.insert({
            'unitid': unitid,
            'nickname': self.nickname,
            'password': password,
            'levels': '1'
        }, 'users')

    def checklogin(self, pwd):
        tools = Tools()
        password = tools.str2md5(pwd)
        num = self.mode.select(
            ["COUNT(1) AS num", "unitid", "levels", "nickname"],
            {
                "text" : "nickname = %s AND password = %s;",
                "format": [self.nickname, password]
            },
            "users",
            True
        )
        if num[0] == 0:
            return False
        self.unitdata = num
        return True
